package cn.mlong.demo.install

import com.intellij.openapi.options.Configurable
import com.intellij.openapi.util.SystemInfo
import com.intellij.ui.components.JBTextField
import com.intellij.ui.dsl.builder.*
import com.intellij.openapi.ui.Messages
import java.io.File
import javax.swing.JComponent
import javax.swing.JFileChooser
import javax.swing.filechooser.FileNameExtensionFilter

class AdbConfigurable : Configurable {
    private val settings = AdbSettings.instance
    private lateinit var adbPathField: JBTextField
    private lateinit var commandField: JBTextField

    override fun createComponent(): JComponent {
        return panel {
            row {
                label("ADB路径:")
                textField()
                    .bindText(settings::adbPath)
                    .also { adbPathField = it.component }
                    .resizableColumn()
                button("浏览...") {
                    selectAdbPath()
                }
                button("自动检测") {
                    autoDetectAdbPath()
                }
            }
            row {
                label("安装命令参数:")
                textField()
                    .bindText(settings::installCommand)
                    .also { commandField = it.component }
                comment("默认: install -r -t (安装并替换现有应用，允许测试包)")
            }
        }
    }

    private fun selectAdbPath() {
        val chooser = JFileChooser().apply {
            fileSelectionMode = JFileChooser.FILES_ONLY
            dialogTitle = "选择adb可执行文件"
            if (SystemInfo.isWindows) {
                fileFilter = FileNameExtensionFilter("ADB可执行文件", "exe")
            }
        }

        if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
            adbPathField.text = chooser.selectedFile.absolutePath
        }
    }

    private fun autoDetectAdbPath() {
        val detectedPath = when {
            SystemInfo.isWindows -> {
                val androidHome = System.getenv("ANDROID_HOME") ?: System.getenv("ANDROID_SDK_ROOT")
                listOfNotNull(
                    androidHome?.let { "$it\\platform-tools\\adb.exe" },
                    "C:\\Program Files\\Android\\Android Studio\\platform-tools\\adb.exe",
                    "C:\\Program Files (x86)\\Android\\android-sdk\\platform-tools\\adb.exe"
                ).firstOrNull { File(it).exists() }
            }
            SystemInfo.isMac || SystemInfo.isLinux -> {
                val androidHome = System.getenv("ANDROID_HOME") ?: System.getenv("ANDROID_SDK_ROOT")
                listOfNotNull(
                    androidHome?.let { "$it/platform-tools/adb" },
                    "/usr/bin/adb",
                    "/usr/local/bin/adb"
                ).firstOrNull { File(it).exists() }
            }
            else -> null
        }

        detectedPath?.let {
            adbPathField.text = it
        } ?: run {
            Messages.showInfoMessage(
                "无法自动检测ADB路径，请手动设置",
                "ADB检测"
            )
        }
    }

    override fun isModified(): Boolean =
        adbPathField.text != settings.adbPath ||
                commandField.text != settings.installCommand

    override fun apply() {
        settings.adbPath = adbPathField.text.trim()
        settings.installCommand = commandField.text.trim()
    }

    override fun reset() {
        adbPathField.text = settings.adbPath
        commandField.text = settings.installCommand
    }

    override fun getDisplayName(): String = "ADB设置"
}